type CacheKey = string;
type CacheValue = any | null;

export default class LRUCache {
  capacity: number;
  cache: Map<CacheKey, CacheValue>;

  constructor(capacity: number) {
    this.capacity = capacity;
    this.cache = new Map();
  }

  get(key: CacheKey) {
    if (this.cache.has(key)) {
      let temp = this.cache.get(key);
      this.cache.delete(key);
      this.cache.set(key, temp);
      return temp;
    }
    return undefined;
  }

  put(key: CacheKey, value: CacheValue) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.capacity) {
      this.cache.delete(this.cache.keys().next().value);
      console.log(`refresh: key:${key} , value:${value}`);
    }
    this.cache.set(key, value);
  }

  toString() {
    console.table(Array.from(this.cache));
  }

  toArr() {
    return Array.from(this.cache);
  }

  has(key: CacheKey) {
    return this.cache.has(key);
  }

  len() {
    return this.cache.size;
  }
}
